﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyFitness.Model;
using System.Windows.Forms;
using MyFitness.View;
using System.Security;
using System.Data.Objects;

namespace MyFitness.Controller
{
    class MyFitnessController : ApplicationContext
    {
        #region Declared Variables
        private MyFitnessDatabaseEntities database;
        private UserController userController;
        
        private int formcount = 0;
        #endregion

        /// <summary>
        /// Constructor
        /// </summary>
        public MyFitnessController()
        {
            database = new MyFitnessDatabaseEntities();
            userController = new UserController(database);
            NewLogin();
        }

        /// <summary>
        /// Creates a new login form view for a user to the MyFitness Application.
        /// </summary>
        public void NewLogin()
        {
            LogonForm logonform = new LogonForm();
            logonform.Closed += new EventHandler(OnFormClosed);
            logonform.OnLogin += new EventHandler(OnLogin);
            logonform.OnNewAccount += new EventHandler(OnNewAccount);
            formcount++;
            logonform.Show();
        }

        /// <summary>
        /// Displays the Main Menu for a User based on a sessino id after they are logged in.
        /// </summary>
        private void ShowMenu(string sessionid)
        {
            MainMenuForm menuform = new MainMenuForm(sessionid);
            menuform.Closed += new EventHandler(OnFormClosed);
            menuform.AccountProfile += new EventHandler(OnAccountProfile);
            menuform.DailyInformation += new EventHandler(OnDailyInformation);
            menuform.PersonalGoals += new EventHandler(OnPersonalGoals);
            menuform.Reports += new EventHandler(OnReports);
            menuform.TipsAndSuggestions += new EventHandler(OnTipsAndSuggestions);
            formcount++;
            menuform.Show();
        }

        #region EventHandlers
        /// <summary>
        /// Traps for form closing events to close the application after all sessions complete.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnFormClosed(object sender, EventArgs e)
        {
            formcount--;
            if( formcount <= 0 )
                ExitThread();
        }

        /// <summary>
        /// Traps for login events, and creates a user session on a valid login.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLogin(object sender, EventArgs e)
        {
            if ((sender.GetType() == typeof(LogonForm)) && (sender != null))
            {
                // Gets the login information from the form
                LogonForm logonform = (LogonForm)sender;
                string username = logonform.Username;
                SecureString password = logonform.Password;

                // Creates a user session from logging in
                string sessionid = userController.Login(username, password);

                // Displays the main menu for the user
                if (sessionid.Length > 0)
                {
                    ShowMenu(sessionid);
                    logonform.Close();
                }
                else
                {
                    logonform.ErrorMessage = "Invalid Username or Password.  Please try again.";
                }
            }
        }

        /// <summary>
        /// Traps for the creation of new accounts.  As a new account is created, a new session will also be created.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnNewAccount(object sender, EventArgs e)
        {
            if( sender.GetType() == typeof(Trainee) )
            {
                Trainee t = (Trainee)sender;
                userController.AddUser(t);

                // Creates a user session from logging in
                string sessionid = userController.Login(t);

                // Displays the main menu for the user
                if (sessionid.Length > 0)
                {
                    ShowMenu(sessionid);
                }
                else
                {
                    // Error message for invalid logon.
                }
            }
        }

        /// <summary>
        /// Traps for viewing the Account Profile Form.  It will load the Trainee Account Profile Form to edit the profile of a user for a given session.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnAccountProfile(object sender, EventArgs e)
        {
            string sessionid = (string)sender;
            User user = userController.GetUserFromSession(sessionid);
            
            if (user != null)
            {
                // Opens the Profile for a Trainee
                if (ObjectContext.GetObjectType(user.GetType()) == typeof(Trainee))
                {
                    TraineeAccountProfileForm accountProfileForm = new TraineeAccountProfileForm((Model.Trainee)user);
                    DialogResult result = accountProfileForm.ShowDialog();
                    Trainee t = accountProfileForm.Trainee;

                    if (result == DialogResult.OK)
                    {
                        if (accountProfileForm.IsNewAccount == true)
                            userController.AddUser(t);
                        else
                            userController.UpdateUser(t);
                    }
                    else
                        userController.DiscardChanges();
                }
            }
        }

        /// <summary>
        /// Traps for viewing the Daily Information Form.  It will load the DailyInfoForm View for a user from a given session.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDailyInformation(object sender, EventArgs e)
        {
            string sessionid = (string)sender;
            string useremail = userController.GetUserEmailFromSession(sessionid);
           
            DailyInfoForm dailyInfoForm = new DailyInfoForm(database, useremail);
            DialogResult result = dailyInfoForm.ShowDialog();
        }

        /// <summary>
        /// Traps for viewing the Personal Goals Form.  It will load the PersonalGoalsForm View for a user from a given session.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPersonalGoals(object sender, EventArgs e)
        {
            string sessionid = (string)sender;
            string useremail = userController.GetUserEmailFromSession(sessionid);

            PersonalGoalsForm personalGoalsForm = new PersonalGoalsForm(database, useremail);
            DialogResult result = personalGoalsForm.ShowDialog();
        }

        /// <summary>
        /// Traps for viewing the Reports Form.  It will load the Reports Form View for a user from a given session.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnReports(object sender, EventArgs e)
        {
            string sessionid = (string)sender;
            string useremail = userController.GetUserEmailFromSession(sessionid);

            ReportsForm reportsForm = new ReportsForm(database, useremail);
            DialogResult result = reportsForm.ShowDialog();
        }

        /// <summary>
        /// Traps for viewing the Tips and Suggestions Form.  It will load the Tips and Suggestions Form View for a user from a given session.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTipsAndSuggestions(object sender, EventArgs e)
        {
            string sessionid = (string)sender;
            string useremail = userController.GetUserEmailFromSession(sessionid);

            TipsAndSuggestionsForm tipsandsuggestionsForm = new TipsAndSuggestionsForm(database, useremail);
            DialogResult result = tipsandsuggestionsForm.ShowDialog();
        }

        #endregion
    }
}
